package hai.com.android_test.widget;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewConfigurationCompat;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.OverScroller;

/**
 * Created by 黄海 on 2016/11/22.
 */

public class StickNavLayout extends LinearLayout {
    private static final String TAG = "StickNavLayout";
    private View mViewTop;
    private View mViewIndicator;
    private ViewPager mViewPager;
    private int mViewTopHeight;
    private OverScroller mScroller;//Scroller 的替代者
    private VelocityTracker mVelocityTracker;//Helper for tracking the velocity of touch events
    private int mTouchSlop;//getScaledTouchSlop是一个距离，表示滑动的时候，手的移动要大于这个距离才开始移动控件
    private int mMinimumFlingVelocity, mMaximumFlingVelocity;//最大最小速率
    private float mLastY;
    private boolean mDraging;
    private boolean mIsTopViewHidden;
    private ViewGroup mInnerScrollView;

    public StickNavLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOrientation(LinearLayout.VERTICAL);
        mScroller = new OverScroller(context);
        mVelocityTracker = VelocityTracker.obtain();
        mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(ViewConfiguration.get(context));
        mMaximumFlingVelocity = ViewConfiguration.get(context).getScaledMaximumFlingVelocity();
        mMinimumFlingVelocity = ViewConfiguration.get(context).getScaledMinimumFlingVelocity();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        Log.d(TAG, "onFinishInflate() called");
//        mViewIndicator = findViewById(R.id.stickNav_indicator);
//        mViewTop = findViewById(R.id.stickNav_top);
//        mViewPager = (ViewPager) findViewById(R.id.stickNav_viewPage);
        if (!(mViewPager instanceof ViewPager)) {
            throw new RuntimeException("R.id.stickNav_viewPage should be used by ViewPage");
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Log.d(TAG, "onMeasure: ");
        ViewGroup.LayoutParams layoutParams = mViewPager.getLayoutParams();
        layoutParams.height = getMeasuredHeight() - mViewIndicator.getMeasuredHeight();

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        Log.d(TAG, "onSizeChanged: ");
        mViewTopHeight = mViewTop.getMeasuredHeight();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float y = event.getY();
        mVelocityTracker.addMovement(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.d(TAG, "onTouchEvent() called with: event = ACTION_DOWN");
                if (!mScroller.isFinished()) {
                    mScroller.abortAnimation();
                }
                mVelocityTracker.clear();
                mLastY = y;
                return true;
            case MotionEvent.ACTION_MOVE:
                Log.d(TAG, "onTouchEvent() called with: event = ACTION_MOVE");
                float dy = y - mLastY;
                if (!mDraging && Math.abs(dy) > mTouchSlop) {
                    //这里如果不加mDraging判断，滑动起来一卡一卡
                    mDraging = true;
                }
                if (mDraging) {
                    scrollBy(0, (int) -dy);
                    mLastY = y;
                }
                break;
            case MotionEvent.ACTION_UP:
                Log.d(TAG, "onTouchEvent() called with: event = ACTION_UP");
                mVelocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity);
                float yVelocity = mVelocityTracker.getYVelocity();
                if (yVelocity > mMinimumFlingVelocity) {
                    fling(-yVelocity);
                }
                mVelocityTracker.clear();
                break;
            case MotionEvent.ACTION_CANCEL:
                Log.d(TAG, "onTouchEvent() called with: event = ACTION_CANCEL");
                if (!mScroller.isFinished()) {
                    mScroller.abortAnimation();
                }
                break;
        }
        return super.onTouchEvent(event);
    }

    private void fling(float yVelocity) {
        mScroller.fling(0, getScrollY(), 0, (int) yVelocity, 0, 0, 0, mViewTopHeight);
        invalidate();
    }

    @Override
    public void scrollTo(int x, int y) {
        if (y < 0) y = 0;
        if (y > mViewTopHeight) y = mViewTopHeight;
        if (y != getScrollY()) super.scrollTo(x, y);
        mIsTopViewHidden = getScrollY() == mViewTopHeight;
    }

    private void getCurrentScrollView() {
        int currentItem = mViewPager.getCurrentItem();
        PagerAdapter adapter = mViewPager.getAdapter();
        Fragment fragment = (Fragment) adapter.instantiateItem(mViewPager, currentItem);
//        mInnerScrollView = (ViewGroup) fragment.getView().findViewById(R.id.stickNav_innerScrollView);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        Log.d(TAG, "onInterceptTouchEvent: "+ev.getAction());
        float y = ev.getY();
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mLastY = y;
                break;
            case MotionEvent.ACTION_MOVE:
                float dy = y - mLastY;
                getCurrentScrollView();
                if (Math.abs(dy) > mTouchSlop) {
                    mDraging = true;
                    if (!mIsTopViewHidden || mInnerScrollView.getScrollY() == 0 && dy < 0) {
                        return true;
                    }
                }
                break;

        }
        return super.onInterceptTouchEvent(ev);
    }
    /**
     * 这个方法可以不重写，重写了下拉的时候有回弹现象，
     */
//    @Override
//    public void computeScroll() {
//        if (mScroller.computeScrollOffset()) {
//            scrollBy(0, mScroller.getCurrY());
//            invalidate();
//        }
//    }

}
